import React, { useState } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent } from '@/components/ui/card';
import { Loader2, Sparkles, Plus } from 'lucide-react';
import { toast } from 'sonner';
import { sendChatStream } from '@/utils/ernieChat';
import { useVocabulary } from '@/contexts/VocabularyContext';
import type { Category, Word } from '@/types/vocabulary';

interface AddWordDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onAddWords: (words: Omit<Word, 'id'>[]) => void;
}

interface GeneratedWord {
  english: string;
  chinese: string;
  category: Category;
  selected: boolean;
}

const AddWordDialog: React.FC<AddWordDialogProps> = ({ open, onOpenChange, onAddWords }) => {
  const { categories, addCategory } = useVocabulary();
  const [activeTab, setActiveTab] = useState<'smart' | 'manual'>('smart');

  // 智能生成模式状态
  const [inputWords, setInputWords] = useState('');
  const [generatedWords, setGeneratedWords] = useState<GeneratedWord[]>([]);
  const [isGenerating, setIsGenerating] = useState(false);
  const [aiResponse, setAiResponse] = useState('');

  // 手动添加模式状态
  const [manualWord, setManualWord] = useState({
    english: '',
    chinese: '',
    definition: '',
    category: '日常生活' as Category,
  });

  // 新增类别状态
  const [showNewCategoryInput, setShowNewCategoryInput] = useState(false);
  const [newCategoryName, setNewCategoryName] = useState('');

  const handleGenerateWords = async () => {
    if (!inputWords.trim()) {
      toast.error('请输入一些单词');
      return;
    }

    setIsGenerating(true);
    setAiResponse('');
    setGeneratedWords([]);

    const APP_ID = import.meta.env.VITE_APP_ID;

    const prompt = `请根据用户输入的单词"${inputWords}"，生成10个相关的英语单词。
要求：
1. 生成的单词应该与输入的单词在主题、词性或使用场景上相关
2. 每个单词必须包含：英文单词、中文释义、所属类别（从以下类别中选择：日常生活、商务职场、学术教育、旅游出行、科技数码）
3. 严格按照以下JSON格式输出，不要包含任何其他文字说明：
[
  {"english": "单词", "chinese": "中文释义", "category": "类别"},
  ...
]`;

    let fullResponse = '';

    try {
      await sendChatStream({
        endpoint: '/api/miaoda/runtime/apicenter/source/proxy/ernietextgenerationchat',
        apiId: APP_ID,
        messages: [
          {
            role: 'user',
            content: prompt,
          },
        ],
        onUpdate: (content: string) => {
          fullResponse = content;
          setAiResponse(content);
        },
        onComplete: () => {
          setIsGenerating(false);
          parseGeneratedWords(fullResponse);
        },
        onError: (error: Error) => {
          setIsGenerating(false);
          toast.error('生成失败：' + error.message);
        },
      });
    } catch (error) {
      setIsGenerating(false);
      toast.error('生成失败，请重试');
    }
  };

  const parseGeneratedWords = (response: string) => {
    try {
      // 尝试从响应中提取JSON数组
      const jsonMatch = response.match(/\[[\s\S]*\]/);
      if (jsonMatch) {
        const parsed = JSON.parse(jsonMatch[0]);
        if (Array.isArray(parsed)) {
          const words: GeneratedWord[] = parsed.map((item) => ({
            english: item.english || '',
            chinese: item.chinese || '',
            category: (item.category as Category) || '日常生活',
            selected: true,
          }));
          setGeneratedWords(words);
          toast.success(`成功生成 ${words.length} 个相关单词`);
        }
      } else {
        toast.error('无法解析生成的单词，请重试');
      }
    } catch (error) {
      toast.error('解析生成结果失败，请重试');
    }
  };

  const handleToggleWord = (index: number) => {
    setGeneratedWords((prev) =>
      prev.map((word, i) => (i === index ? { ...word, selected: !word.selected } : word))
    );
  };

  const handleAddGeneratedWords = () => {
    const selectedWords = generatedWords.filter((word) => word.selected);
    if (selectedWords.length === 0) {
      toast.error('请至少选择一个单词');
      return;
    }

    const wordsToAdd = selectedWords.map((word) => ({
      english: word.english,
      chinese: word.chinese,
      category: word.category,
      isCustom: true,
    }));

    onAddWords(wordsToAdd);

    // 重置状态
    setInputWords('');
    setGeneratedWords([]);
    setAiResponse('');
    onOpenChange(false);
  };

  const handleAddManualWord = () => {
    if (!manualWord.english.trim() || !manualWord.chinese.trim()) {
      toast.error('请填写英文单词和中文释义');
      return;
    }

    onAddWords([
      {
        english: manualWord.english.trim(),
        chinese: manualWord.chinese.trim(),
        category: manualWord.category,
        isCustom: true,
      },
    ]);

    // 重置表单
    setManualWord({
      english: '',
      chinese: '',
      definition: '',
      category: '日常生活',
    });
    onOpenChange(false);
  };

  const handleAddNewCategory = () => {
    if (!newCategoryName.trim()) {
      toast.error('请输入类别名称');
      return;
    }

    if (categories.includes(newCategoryName.trim())) {
      toast.error('该类别已存在');
      return;
    }

    addCategory(newCategoryName.trim());
    setManualWord({ ...manualWord, category: newCategoryName.trim() });
    setNewCategoryName('');
    setShowNewCategoryInput(false);
    toast.success('新类别添加成功');
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="text-2xl">添加新单词</DialogTitle>
          <DialogDescription>选择添加方式：智能生成或手动添加</DialogDescription>
        </DialogHeader>

        <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'smart' | 'manual')}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="smart" className="flex items-center gap-2">
              <Sparkles className="w-4 h-4" />
              智能生成
            </TabsTrigger>
            <TabsTrigger value="manual" className="flex items-center gap-2">
              <Plus className="w-4 h-4" />
              手动添加
            </TabsTrigger>
          </TabsList>

          <TabsContent value="smart" className="space-y-4 mt-4">
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>输入单词或主题</Label>
                <Textarea
                  placeholder="例如：apple, computer, travel 或输入一个主题如'办公室'"
                  value={inputWords}
                  onChange={(e) => setInputWords(e.target.value)}
                  rows={3}
                  disabled={isGenerating}
                />
              </div>

              <Button
                onClick={handleGenerateWords}
                disabled={isGenerating || !inputWords.trim()}
                className="w-full"
              >
                {isGenerating ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    正在生成相关单词...
                  </>
                ) : (
                  <>
                    <Sparkles className="w-4 h-4 mr-2" />
                    生成相关单词
                  </>
                )}
              </Button>

              {isGenerating && aiResponse && (
                <Card>
                  <CardContent className="pt-6">
                    <p className="text-sm text-gray-600 whitespace-pre-wrap">{aiResponse}</p>
                  </CardContent>
                </Card>
              )}

              {generatedWords.length > 0 && (
                <div className="space-y-3">
                  <Label>选择要添加的单词（{generatedWords.filter((w) => w.selected).length} 个已选）</Label>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 max-h-96 overflow-y-auto">
                    {generatedWords.map((word, index) => (
                      <Card
                        key={index}
                        className={`cursor-pointer transition-all ${
                          word.selected ? 'border-indigo-500 bg-indigo-50' : 'hover:border-gray-400'
                        }`}
                        onClick={() => handleToggleWord(index)}
                      >
                        <CardContent className="p-4">
                          <div className="flex items-start gap-3">
                            <Checkbox checked={word.selected} onCheckedChange={() => handleToggleWord(index)} />
                            <div className="flex-1">
                              <div className="font-semibold text-gray-900">{word.english}</div>
                              <div className="text-sm text-gray-600">{word.chinese}</div>
                              <div className="text-xs text-gray-500 mt-1">{word.category}</div>
                            </div>
                          </div>
                        </CardContent>
                      </Card>
                    ))}
                  </div>

                  <Button onClick={handleAddGeneratedWords} className="w-full" size="lg">
                    添加选中的单词（{generatedWords.filter((w) => w.selected).length} 个）
                  </Button>
                </div>
              )}
            </div>
          </TabsContent>

          <TabsContent value="manual" className="space-y-4 mt-4">
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="english">英文单词 *</Label>
                <Input
                  id="english"
                  placeholder="例如：apple"
                  value={manualWord.english}
                  onChange={(e) => setManualWord({ ...manualWord, english: e.target.value })}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="chinese">中文释义 *</Label>
                <Input
                  id="chinese"
                  placeholder="例如：苹果"
                  value={manualWord.chinese}
                  onChange={(e) => setManualWord({ ...manualWord, chinese: e.target.value })}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="definition">详细定义（可选）</Label>
                <Textarea
                  id="definition"
                  placeholder="输入单词的详细定义或例句"
                  value={manualWord.definition}
                  onChange={(e) => setManualWord({ ...manualWord, definition: e.target.value })}
                  rows={3}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="category">类别</Label>
                {!showNewCategoryInput ? (
                  <div className="flex gap-2">
                    <Select
                      value={manualWord.category}
                      onValueChange={(value: Category) => setManualWord({ ...manualWord, category: value })}
                    >
                      <SelectTrigger id="category" className="flex-1">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {categories.filter(cat => cat !== '全部类别').map((category) => (
                          <SelectItem key={category} value={category}>
                            {category}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <Button
                      type="button"
                      variant="outline"
                      size="icon"
                      onClick={() => setShowNewCategoryInput(true)}
                      title="新增类别"
                    >
                      <Plus className="w-4 h-4" />
                    </Button>
                  </div>
                ) : (
                  <div className="flex gap-2">
                    <Input
                      placeholder="输入新类别名称"
                      value={newCategoryName}
                      onChange={(e) => setNewCategoryName(e.target.value)}
                      onKeyPress={(e) => {
                        if (e.key === 'Enter') {
                          handleAddNewCategory();
                        }
                      }}
                    />
                    <Button
                      type="button"
                      onClick={handleAddNewCategory}
                      size="sm"
                    >
                      确定
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => {
                        setShowNewCategoryInput(false);
                        setNewCategoryName('');
                      }}
                      size="sm"
                    >
                      取消
                    </Button>
                  </div>
                )}
              </div>

              <Button onClick={handleAddManualWord} className="w-full" size="lg">
                添加单词
              </Button>
            </div>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
};

export default AddWordDialog;
